package com.elepro.shoppingmall.config.security.handler;

import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class FailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
        ResultMsg resultMsg;

        if (e instanceof UsernameNotFoundException) {
            resultMsg = ResultMsg.fail("账号不存在");
        }
        else if (e instanceof BadCredentialsException) {
            resultMsg = ResultMsg.fail("密码错误");
        }
        else {
            resultMsg = ResultMsg.fail(e.getMessage());
        }

        ResultMsg.returnResponse(resultMsg, httpServletResponse);
    }
}
